package com.evon.yardmanagement.ui.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.evon.yardmanagement.exception.YardManagementException;
import com.evon.yardmanagement.exception.YardManagementException.ExceptionType;
import com.evon.yardmanagement.model.Oem;
import com.evon.yardmanagement.model.Section;
import com.evon.yardmanagement.model.Yard;
import com.evon.yardmanagement.model.YardMapping;
import com.evon.yardmanagement.security.YardSecurityManager;
import com.evon.yardmanagement.service.OEMService;
import com.evon.yardmanagement.service.ParkingSlotsService;
import com.evon.yardmanagement.service.SectionManagementService;
import com.evon.yardmanagement.service.UtilityService;
import com.evon.yardmanagement.service.YardManagementService;
import com.evon.yardmanagement.transformer.YardTransformer;
import com.evon.yardmanagement.ui.dto.CountryDTO;
import com.evon.yardmanagement.ui.dto.OemDTO;
import com.evon.yardmanagement.ui.dto.YardDTO;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

public class ManageYardAction extends ActionSupport implements
ApplicationAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public ManageYardAction () {
		
		this.availableYard = new ArrayList<YardDTO>();
		YardDTO yardDTO = new YardDTO();
		yardDTO.setName(NEW);
		yardDTO.setId(0);
		availableYard.add(yardDTO);
		countryList = new ArrayList<CountryDTO>(); 
		oemList = new ArrayList<OemDTO>();
		/*countryList.add(new Country(1, "India")); 
		        
		countryList.add(new Country(2, "USA")); 
		        
		countryList.add(new Country(3, "France")); */
		
		listYardType = new ArrayList<String>();
		listYardType.add(MANUFACTURER);
		listYardType.add(PORT);
		
		/*newList = new ArrayList<String>();
		newList.add(NEW);*/

	}
	private Map<String, Object> globalData;
	
	private List<YardDTO> availableYard;
	//private OemDTO oemDto;
	private  List<CountryDTO> countryList ;
	private List<OemDTO> oemList;
	
	private int oemType;
	
	private YardDTO yardDetail; 
	private int hidYardId;
	
	private String hidNewYard;
	
	//private String hidActiveCheckInd;
	
	private String yardType;
	
	private String selectedYard;
	
	private String chkActive;
	
	
	public String getChkActive() {
		return chkActive;
	}

	/*public String getHidActiveCheckInd() {
		return hidActiveCheckInd;
	}

	public void setHidActiveCheckInd(String hidActiveCheckInd) {
		this.hidActiveCheckInd = hidActiveCheckInd;
	}*/

	public String getHidNewYard() {
		return hidNewYard;
	}

	@SkipValidation
	public void setHidNewYard(String hidNewYard) {
		this.hidNewYard = hidNewYard;
	}

	@SkipValidation
	public void setChkActive(String chkActive) {
		this.chkActive = chkActive;
	}

	public String getSelectedYard() {
		return selectedYard;
	}

	@SkipValidation
	public void setSelectedYard(String selectedYard) {
		this.selectedYard = selectedYard;
	}

	

	public String getYardType() {
		return yardType;
	}

	@SkipValidation
	public void setYardType(String yardType) {
		this.yardType = yardType;
	}

	public YardDTO getYardDetail() {
		return yardDetail;
	}

	@SkipValidation
	public void setYardDetail(YardDTO yardDetail) {
		this.yardDetail = yardDetail;
	}

	

	public int getHidYardId() {
		return hidYardId;
	}

	@SkipValidation
	public void setHidYardId(int hidYardId) {
		this.hidYardId = hidYardId;
	}

	public int getOemType() {
		return oemType;
	}

	@SkipValidation
	public void setOemType(int oemType) {
		this.oemType = oemType;
	}

	private List<String> listYardType;

	/*private List<String> newList;
	
	public List<String> getNewList() {
		return newList;
	}

	public void setNewList(List<String> newList) {
		this.newList = newList;
	}*/



	public List<OemDTO> getOemList() {
		return oemList;
	}
	@SkipValidation
	public void setOemList(List<OemDTO> oemList) {
		this.oemList = oemList;
	}



	private static final String MANUFACTURER = "M";
	private static final String PORT = "P";
	
	private static final String NEW = "NEW";

	private String country;
	
	
	

	public List<String> getListYardType() {
		return listYardType;
	}
	@SkipValidation
	public void setListYardType(List<String> listYardType) {
		this.listYardType = listYardType;
	}

	public List<CountryDTO> getCountryList() {
		return countryList;
	}
	@SkipValidation
	public void setCountryList(List<CountryDTO> countryList) {
		this.countryList = countryList;
	}

	public String getCountry() {
		return country;
	}
	@SkipValidation
	public void setCountry(String country) {
		this.country = country;
	}

	@SkipValidation
	public String populate() {     
		
		oemList = OEMService.getAllOem();
		countryList = UtilityService.getCountries();

		globalData.put("countryList", countryList);
		globalData.put("oemList", oemList);

		return "populate"; 

	} 
@SkipValidation
	public String execute() throws Exception {
		//populate();
		oemList = (List<OemDTO>)globalData.get("oemList");
		countryList = (List<CountryDTO>) globalData.get("countryList");
		yardDetail = new YardDTO();
		hidNewYard = "";
		YardManagementService service = new YardManagementService();		
		List<Yard> yards = service.getYardsByOemId(oemType);
		YardDTO yardDTO;
		int i =0;
		for(Yard yard : yards) {
			yardDTO = YardTransformer.transform(yard);
			availableYard.add(yardDTO);
			i++;
		}
		globalData.put("availableYard", availableYard);
		return SUCCESS;
	}

private boolean validateYard() {
	boolean success = true;
	if ("0".equals(country)) {
		//errMsg.append("Yard Name cannot be left empty");
		addActionMessage("Country cannot be left empty");
		success = false;
	}
	if (oemType==0) {
		//errMsg.append("Yard Name cannot be left empty");
		addActionMessage("OEM cannot be left empty");
		success = false;
	}
	
	if (yardType==null) {
		//errMsg.append("Yard Name cannot be left empty");
		addActionMessage("Yard Type cannot be left empty");
		success = false;	
	}
	
	return success;
}
@SkipValidation
	public String yardDetails() throws Exception {
		
		//populate();
		//execute();
		oemList = (List<OemDTO>)globalData.get("oemList");
		countryList = (List<CountryDTO>) globalData.get("countryList");
		availableYard = (List<YardDTO>)globalData.get("availableYard");
		
		
		yardDetail = new YardDTO();
		for (YardDTO yard : getAvailableYard()) {
			if (NEW.equals(selectedYard)) {
				hidNewYard = "new";
				break;
			}else if (selectedYard.equals(yard.getName())) {
				hidNewYard = "";
				yardDetail = yard;
				break;
			}  
			
		}
		return SUCCESS;
	}

	@Validations(
			requiredStrings = { 
					@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "yardDetail.name", message = "Please enter Yard Name."),
					@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "yardDetail.city", message = "Please enter City."),
					@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "yardDetail.phone", message = "Please enter Phone."),
					@RequiredStringValidator(type = ValidatorType.FIELD, fieldName = "yardDetail.address", message = "Please enter Address.")
			},
			regexFields = {
					@RegexFieldValidator(fieldName="yardDetail.phone", expression="^[0-9]+",message="Phone can only be numeric", type=ValidatorType.FIELD),
					@RegexFieldValidator(fieldName ="yardDetail.name", expression = "^[a-zA-Z]+$", message = "Only Character is allowed for Yard name."),
					@RegexFieldValidator(fieldName ="yardDetail.city", expression = "^[a-zA-Z]+$", message = "Only Character is allowed for City."),
					@RegexFieldValidator(fieldName ="yardDetail.address", expression = "^[a-zA-Z]+$", message = "Only Character is allowed for Address.")
					}
	)
	public String submit() {
		try {
			//execute();
			oemList = (List<OemDTO>)globalData.get("oemList");
			countryList = (List<CountryDTO>) globalData.get("countryList");
			availableYard = (List<YardDTO>)globalData.get("availableYard");
			/*if (!validateYardDetails()){
				return SUCCESS;
			}*/
			
			if (!validateYard()) {
				return SUCCESS;
			}
			
			if (!"new".equals(hidNewYard) /*&& "true".equals(hidActiveCheckInd)*/) {
				if (yardDetail.isActive){

					SectionManagementService service = new SectionManagementService();
					ParkingSlotsService slotsService = new ParkingSlotsService();

					List<Section> sections = service.getSectionBySectionId(yardDetail.getId());

					//	if (!sections.isEmpty()) {
					
					service.setActiveSectionByYardId(yardDetail.getId());
					addActionMessage("All sections for yard "+ yardDetail.getName()+" activated successfully");
					//	}
					
				} else {
					SectionManagementService service = new SectionManagementService();
					ParkingSlotsService slotsService = new ParkingSlotsService();
					List<Section> sections = service.getSectionBySectionId(yardDetail.getId());

					//if (!sections.isEmpty()) {
					service.setDeActiveSectionByYardId(yardDetail.getId());
					addActionMessage("All sections for yard "+ yardDetail.getName()+" deactivated successfully");
					//	slotsService.setDeActiveParkingSlotByYardId(yardDetail.getId());
					//}
					System.out.println("deactivate");
				}
			}

			YardMapping yardMapping = new YardMapping();
		Oem oem = new Oem();
		oem.setId(oemType);
		yardMapping.setOem(oem);
		/*Vendor vendor = new Vendor();
		vendor.setId(1);*/
		yardMapping.setVendor(YardSecurityManager.getCurrentVendor());
		//yardMapping.setVendor(vendor);
		//yardMapping.setYardId(yardDetail.getYardId());
		//yardDetail.setYardMapping(yardMapping);
		yardDetail.setYardType(getYardType());
		Yard yard = YardTransformer.transformCreateYard(yardDetail);
		yard.setYardMapping(yardMapping);
		YardManagementService service = new YardManagementService();
		boolean success= service.addYard(yard);
			yardMapping.setYardId(yard.getId());
			if (yardDetail.getId()==0) {
				success= service.addYardMapping(yardMapping);
			}
			addActionMessage("Yard details added successfully");
			
			return SUCCESS;
		} catch (YardManagementException yme) {
			if (ExceptionType.RECOVERABLE.equals(yme.getType())) {
				addActionMessage("Error while setting yard details, please contact administrator");
				return INPUT;
			} else {
				return ERROR;
			}

		}catch (Exception exe) {
			addActionMessage("Critival Error occured, please contact administrator");
			return ERROR;
		}
	}
	
	
	private boolean validateYardDetails() {
		boolean success = true;
		YardDTO yardDTO = getYardDetail();
		//StringBuilder errMsg = new StringBuilder("");
		if (yardDTO!=null && (yardDTO.getName()==null || "".equals(yardDTO.getName().trim()))) {
			//errMsg.append("Yard Name cannot be left empty");
			addActionMessage("Yard Name cannot be left empty");
			success = false;
		}
		if (yardDTO!=null && (yardDTO.getAddress()==null || "".equals(yardDTO.getAddress().trim()))) {
			//errMsg.append("Yard Address cannot be left empty");
			addActionMessage("Yard Address cannot be left empty");
			success = false;
		}
		if (yardDTO!=null && (yardDTO.getCity()==null || "".equals(yardDTO.getCity().trim()))) {
			//errMsg.append("Yard City cannot be left empty\n");
			addActionMessage("Yard City cannot be left empty");
			//addActionMessage(errMsg.toString());
			success = false;
		}
		
		/*if (!success) {
			addActionMessage(errMsg.toString());
		}*/
		
		return success;
		
	}
	/*public String manageActive() throws Exception{
		execute();
		if (yardDetail.isActive){
			
			SectionManagementService service = new SectionManagementService();
			ParkingSlotsService slotsService = new ParkingSlotsService();
			
			List<Section> sections = service.getSectionBySectionId(yardDetail.getId());
			
		//	if (!sections.isEmpty()) {
				ParkingSlotsService psService = new ParkingSlotsService();
				//SectionDTO sectionDTO = null;
				List<SectionDTO> sectionDtoList = new ArrayList<SectionDTO>();
				SectionDTO sectionDTO = null;
				Section sectionModel = null;
				List<Section> saveActSection = new ArrayList<Section>();
				for (Section section : sections) {
					sectionDTO = SectionTransformer.transformToDTO(section);
					sectionDTO.setActive(true);
					sectionDtoList.add(sectionDTO);	
				}

				for (SectionDTO sectionDTO2 : sectionDtoList) {
					sectionModel = SectionTransformer.transformCreateSection(sectionDTO2);
					saveActSection.add(sectionModel);
				}

				boolean success = service.setActiveSectionBySectionId(saveActSection);
				service.setActiveSectionByYardId(yardDetail.getId());
		//	}
			Yard yard = YardTransformer.transformCreateYard(yardDetail);
			YardManagementService service1 = new YardManagementService();
			boolean success1= service1.addYard(yard);
			System.out.println("active");
		} else {
			SectionManagementService service = new SectionManagementService();
			ParkingSlotsService slotsService = new ParkingSlotsService();
			List<Section> sections = service.getSectionBySectionId(yardDetail.getId());
			
			//if (!sections.isEmpty()) {
				service.setDeActiveSectionByYardId(yardDetail.getId());
			//	slotsService.setDeActiveParkingSlotByYardId(yardDetail.getId());
			//}
			System.out.println("deactivate");
		}
		return SUCCESS;
	}
*/
	public List<YardDTO> getAvailableYard() {
		return availableYard;
	}



	public void setAvailableYard(List<YardDTO> availableYard) {
		this.availableYard = availableYard;
	}
	@SkipValidation
	public void setApplication(Map<String, Object> application) {
		this.globalData = application;
		
	}

	

}
